from rest_framework import status
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from rest_framework.generics import ListAPIView

from meiduo_admin.serializers.images_serializer import SKUImageSerializer
from meiduo_admin.serializers.skus_serializer import SKUSerializer, CategorieSerialzier, GoodsSimpleSerialzier, \
    SPUSpecificationSerializer
from meiduo_admin.utils import PageNum
from goods.models import SKU, GoodsCategory, SPU, SPUSpecification, SKUImage


class SKUViewSet(ModelViewSet):
    """
        SKU表数据的增删改查
    """
    serializer_class = SKUSerializer
    # queryset = SKU.objects.all().order_by('id')
    pagination_class = PageNum

    def categories(self, request):
        # 1、查询三级分类信息
        data = GoodsCategory.objects.filter(subs=None).order_by('id')

        # 序列化返回三级分类
        ser = CategorieSerialzier(data, many=True)

        return Response(ser.data)

    def goodssimple(self, request):
        # 查询spu表数据
        data = SPU.objects.all().order_by('id')
        ser = GoodsSimpleSerialzier(data, many=True)
        return Response(ser.data)

    def spuspecification(self, request, pk):
        # 查询spu商品的所有规格
        data = SPUSpecification.objects.filter(spu_id=pk).order_by('id')

        # 序列化返回
        ser = SPUSpecificationSerializer(data, many=True)
        return Response(ser.data)

    def get_queryset(self):
        # 根据传递参数不同，传递不同数据
        keyword = self.request.query_params.get('keyword')

        if keyword == '' or keyword is None:
            # 如果keyword为空查询所有数据
            return SKU.objects.all().order_by('id')

        else:

            return SKU.objects.filter(name__contains=keyword).order_by('id')


